import { Component,OnInit } from '@angular/core';
import { Router} from '@angular/router';


import { Hero } from './Hero'
import { HeroServcie } from './hero.service';



@Component({
  moduleId : module.id,
  selector: 'my-heroes',
  templateUrl: './heroes.component.html',
  styleUrls : ['./heroes.component.css'],
})
export class HeroesComponent implements OnInit {

  heros: Hero[];
  selectedHero: Hero;
  //选中之后的对象数据
  onSelect(hero: Hero): void {
    this.selectedHero = hero;
  }
  constructor(
    private heroService: HeroServcie,
    private router :Router
    ) { };

  getHeroes():void {
    this.heroService.getHeros().then(heros =>this.heros = heros);
  }

  //导航至详情页面，传递带id的url参数
  gotoDetail():void{
    this.router.navigate(['/detail',this.selectedHero.id]);
  }

  add(name:string):void{
    name = name.trim();
    if (!name) {return ;}
    this.heroService.create(name)
      .then(hero => {this.heros.push(hero);
              this.selectedHero = null;
            });
  }


  delete(hero:Hero):void{
    this.heroService.delete(hero.id)
      .then(() => {
        this.heros = this.heros.filter(h => h !== hero);
        if (this.selectedHero === hero) {this.selectedHero = null ;}
      });
  }
  ngOnInit() {
    //Called after the constructor, initializing input properties, and the first call to ngOnChanges.
    //Add 'implements OnInit' to the class.
    this.getHeroes();
  }

}

